#include "seqlist.h"

void SeqlistInit(Seqlist *sql)
{
    sql->a = NULL;
    sql->size = 0;
    sql->capacity = 0;
}

void SeqListCheckCapacity(Seqlist *sql)
{
    assert(sql);
    //判断容量是否已满
    if (sql->size == sql->capacity)
    {
        size_t newCapacity = sql->capacity == 0 ? 4 : sql->capacity * 2;
        SLDateType *ps = (SLDateType *)realloc(sql->a, sizeof(SLDateType) * newCapacity);
        //判断是否扩容成功 -> realloc没有成功将返回NULL
        if (ps == NULL)
        {
            printf("realloc faily!!!\n");
            exit(EXIT_FAILURE);
        }
        else
        {
            sql->a = ps;
            sql->capacity = newCapacity;
        }
    }
}

void SeqlistDestroy(Seqlist *sql)
{
    assert(sql);
    free(sql->a);
    sql->a = NULL;
    sql->size = 0;
    sql->capacity = 0;
}

void SeqlistPrint(const Seqlist *sql)
{
    assert(sql);
    for (int i = 0; i < sql->size; ++i)
    {
        printf("%d ", sql->a[i]);
    }
    printf("\n");
}

void SeqlistInsert(Seqlist *sql, size_t pos, SLDateType x)
{
    assert(sql);
    assert(pos <= sql->size);
    SeqListCheckCapacity(sql);

    size_t end = sql->size;
    while (end > pos)
    {
        sql->a[end] = sql->a[end - 1];
        --end;
    }
    sql->a[pos] = x;
    sql->size++;
}

void SeqlistErase(Seqlist *sql, size_t pos)
{
    assert(sql);
    assert(pos < sql->size);

    size_t begin = pos + 1;
    while (begin < sql->size)
    {
        sql->a[begin - 1] = sql->a[begin];
        ++begin;
    }
    sql->size--;
}

void SeqlistPushBack(Seqlist *sql, SLDateType x)
{
    assert(sql);
    SeqlistInsert(sql, sql->size, x);
}

void SeqlistPopBack(Seqlist *sql)
{
    assert(sql);
    SeqlistErase(sql, sql->size - 1);
}

void SeqlistPushFront(Seqlist *sql, SLDateType x)
{
    assert(sql);
    SeqlistInsert(sql, 0, x);
}

void SeqlistPopFront(Seqlist *sql)
{
    assert(sql);
    SeqlistErase(sql, 0);
}

int main()
{
    Seqlist s;
    SeqlistInit(&s);
    SeqlistPushBack(&s, 1);
    SeqlistPushBack(&s, 2);
    SeqlistPushBack(&s, 3);
    SeqlistPushBack(&s, 4);
    SeqlistPushBack(&s, 5);
    SeqlistPopBack(&s);

    SeqlistPushFront(&s, 0);
    SeqlistPushFront(&s, -1);

    SeqlistPopFront(&s);
    SeqlistPopFront(&s);
    SeqlistPrint(&s);
    system("pause");
    return 0;
}